//import { defineAsyncComponent } from 'vue'
import store from '@/library/store'
import router from '@/library/router'
import DescPage from '@/layout/DescPage.vue'
import NonePage from '@/layout/NonePage.vue'
const modules = import.meta.glob('../../views/**/**.vue')
//console.dir(modules)
/**
 * 动态添加路由
 * routes= [{path: '', name: '', component: '', meta: {auth: true, }, redirect: ''}]
 * router.hasRoute   router.removeRoute  router.addRoute
 *
 *
 */
const addRoutes = (routes, parentName = 'Index') => {
  routes.forEach(item => {
    if (item.path && item.component) {

      let module = NonePage
      if (item.children && item.children.length) {
        module = item.type=='node'? NonePage : DescPage
      } else {
        const componentString = item.component.replace(/^\/+/, ''),   // 过滤字符串前面所有 '/' 字符
          componentPath = componentString.replace(/\.\w+$/, '')          // 过滤掉后缀名，为了让 import 加入 .vue ，不然会有警告提示...
        module = modules[`../../views/${componentPath}.vue`]
      }

      const route = {
        path: item.path,
        name: item.code,
        component: module,
        meta: { title: item.name, auth: item.auth, desc:'好东西一定要大家一起用'}
      }
      //
      parentName ? router.addRoute(parentName, route) : router.addRoute(route)
      //
      //router.options.routes.push(route)
      if (item.children && item.children.length) {
        addRoutes(item.children, item.code)
      }
    }
  })
}

/**dynamic
 * 注册路由
 * 用户切换账号需移除 sessionStorage 中的 routerMap 数据
 */
const registerAsyncRoutes = () => {
  // console.info(sessionStorage.getItem('vuex'))
  const vuexData = sessionStorage.getItem('vuex')
  if (vuexData !== null) {
    const vuex = JSON.parse(vuexData)
    const routerMap = vuex.menu?.navMenus
    if (routerMap !== undefined) {
      addRoutes(routerMap)
    }
  }
  store.dispatch('asyncHasRoute', true)
}
export default registerAsyncRoutes